package com.zengyu.toiusuapplication.change;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;
import com.zengyu.toiusuapplication.LoginActivity;
import com.zengyu.toiusuapplication.MainActivity;
import com.zengyu.toiusuapplication.R;
import com.zengyu.toiusuapplication.Utils.SessionManager;
import com.zengyu.toiusuapplication.api.ApiClient;
import com.zengyu.toiusuapplication.api.ApiService;
import com.zengyu.toiusuapplication.DTO.ChangePasswordRequest;
import com.zengyu.toiusuapplication.DTO.ChangePasswordResponse;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

//密码修改逻辑
public class PasswordActivity extends AppCompatActivity {
    private TextInputEditText etOldPassword, etNewPassword, etConfirmPassword;
    MaterialButton buttonSave;
    MaterialButton passwordReset;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_password);

        etOldPassword = findViewById(R.id.etOldPassword);
        etNewPassword = findViewById(R.id.etNewPassword);
        etConfirmPassword = findViewById(R.id.etConfirmPassword);

        // ✅ 初始化 Toolbar
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        buttonSave = findViewById(R.id.buttonSave);
        passwordReset = findViewById(R.id.passwordreset);

        // 点击确认按钮开始加载动画并执行修改密码逻辑
        buttonSave.setOnClickListener(v -> {
            changePassword(buttonSave);
        });

        // 点击重置按钮清空输入框
        passwordReset.setOnClickListener(v -> {
            etOldPassword.setText("");
            etNewPassword.setText("");
            etConfirmPassword.setText("");
        });

        // ✅ 显示返回箭头
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setTitle("密码修改"); // 可选：动态设置标题
        }
    }

    // ✅ 处理返回按钮点击
    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed(); // 返回上一页
        return true;
    }

    private void changePassword(MaterialButton buttonSave) {
        Drawable icon = buttonSave.getIcon();
        String oldPassword = etOldPassword.getText().toString().trim();
        String newPassword = etNewPassword.getText().toString().trim();
        String confirmPassword = etConfirmPassword.getText().toString().trim();

        if (oldPassword.isEmpty() || newPassword.isEmpty() || confirmPassword.isEmpty()) {
            Toast.makeText(this, "所有字段都是必填的", Toast.LENGTH_SHORT).show();
            if (icon instanceof Animatable) ((Animatable) icon).stop();
            return;
        }

        if (!newPassword.equals(confirmPassword)) {
            Toast.makeText(this, "新密码和确认新密码不匹配", Toast.LENGTH_SHORT).show();
            if (icon instanceof Animatable) ((Animatable) icon).stop();
            return;
        }

        if (newPassword.length() < 6) {
            etNewPassword.setError("新密码至少6位");
            if (icon instanceof Animatable) ((Animatable) icon).stop();
            return;
        }
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            buttonSave.setText("");
            // 启动动画
            if (icon instanceof Animatable) {
                Log.d("PasswordActivity", "图标支持动画");
                ((Animatable) icon).start();
            } else {
                Toast.makeText(this, "图标无法播放动画，请检查资源引用", Toast.LENGTH_SHORT).show();
            }
            // 执行密码修改
        }, 1000);

        SessionManager sessionManager = new SessionManager(this);
        String token = sessionManager.getToken();
        if (token.isEmpty()) {
            Toast.makeText(this, "请重新登录", Toast.LENGTH_SHORT).show();
            if (icon instanceof Animatable) ((Animatable) icon).stop();
            return;
        }

        ApiService apiService = ApiClient.getApiService();
        ChangePasswordRequest request = new ChangePasswordRequest();
        request.setOldPassword(oldPassword);
        request.setNewPassword(newPassword);

        Call<ChangePasswordResponse> call = apiService.changePassword(request);
        call.enqueue(new Callback<ChangePasswordResponse>() {
            @Override
            public void onResponse(Call<ChangePasswordResponse> call, Response<ChangePasswordResponse> response) {
                if (response.isSuccessful()) {
                    ChangePasswordResponse changePasswordResponse = response.body();
                    if (changePasswordResponse != null && changePasswordResponse.isSuccess()) {
                        Toast.makeText(PasswordActivity.this, "密码修改成功", Toast.LENGTH_SHORT).show();
                        sessionManager.clearAuthToken();
                        Intent intent = new Intent(PasswordActivity.this, LoginActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        Toast.makeText(PasswordActivity.this, "密码修改失败: " + changePasswordResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(PasswordActivity.this, "密码修改失败", Toast.LENGTH_SHORT).show();
                }

                // 停止动画并恢复文字
                if (icon instanceof Animatable) ((Animatable) icon).stop();
                buttonSave.setText("确认");
            }

            @Override
            public void onFailure(Call<ChangePasswordResponse> call, Throwable t) {
                Toast.makeText(PasswordActivity.this, "请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                if (icon instanceof Animatable) ((Animatable) icon).stop();
                buttonSave.setText("确认");
            }
        });
    }
}
